package com.axsoft.jobimp.types;

public class BLK extends DataType {

	public BLK() {
		super(0);
	}
	
	public BLK(final byte[] pBLK) {
		super(0);
		setBLK(pBLK);
	}
	
	
	public void setBLK(final byte[] pBLK) {
		if (pBLK == null) {
			mData = null;
		} else {
			mData = pBLK.clone();
		}
	}
	
	
	public void addBLK(final BLK pBLK) {
		if (pBLK != null) {
			addBytes(pBLK.getData());
		}
	}
	
	public void addBytes(final byte[] pBytes) {
		
		if (pBytes == null) {
			return;
		}
		
		if (mData == null) {
			setBLK(pBytes);
			return;
		}
		
		final byte[] tempData = mData.clone();
		final int length = mData.length + pBytes.length;
		mData = new byte[length];
		
		for (int i = 0; i < tempData.length; i++) {
			setByte(i, tempData[i]);
		}
		
		for (int i = tempData.length; i < pBytes.length + tempData.length; i++) {
			setByte(i, pBytes[i - tempData.length]);
		}
	}
	
	/**
	 * Get 2 bytes at the given position
	 */
	public BLK getWord(final int pPosition) {
		return copyBytes(pPosition, 2);
	}
	
	/**
	 * Get 4 bytes at the given position
	 */
	public BLK getLongWord(final int pPosition) {
		return copyBytes(pPosition, 4);
	}
	
	/**
	 * Get 8 bytes at the given position
	 */
	public BLK getOctaWord(final int pPosition) {
		return copyBytes(pPosition, 8);
	}
	
	/**
	 * Get 2 bytes at the given position
	 */
	public BLK getQuadWord(final int pPosition) {
		return copyBytes(pPosition, 16);
	}
	
	/**
	 * Copy <length> bytes starting from the <position> 
	 */
	public BLK copyBytes(final int pPosition, final int pLength) {
		final byte[] bytes = new byte[pLength];
		
		for (int i = pPosition; i < pPosition + pLength; i++) {
			bytes[i-pPosition] = mData[i];
		}
		
		return new BLK(bytes);
	}
	
}
